from os import stat
from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynUpdate, collectionUpdate
from gridfs import GridFS
from . import dbStallQuery
from bson.objectid import ObjectId
from flask import send_from_directory
from app.settings.base import soft_path
import os

def save_file_to_mongo(content, filename, version, version_desc):
    '''
    上传升级包到数据库
    '''
    try:
        mg_client = get_mongo_client()
        db = mg_client[dbSynUpdate]
        fs = GridFS(db, collectionUpdate)
        # filename字段是固定的，可增加其他字段
        cond = {'filename': filename}
        bExist = fs.exists(cond)
        files_id = '0'
        if bExist is True:
            return files_id
        else:
            filter_condition = {'filename': filename, 'version': version, 'version_desc': version_desc}
            files_id = fs.put(data=content, **filter_condition)

        return files_id
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def get_upgrade_apkVersion(diningNo, stallNo, softVersion, deviceNo):
    '''
    获取APP升级版本
    '''
    try:
        mg_client = get_mongo_client()
        # 查找升级状态
        state = dbStallQuery.getUpgradeState(diningNo, stallNo, deviceNo)
        if state is None:
            return None, '', ''
                
        db = mg_client[dbSynUpdate]
        fs = GridFS(db, collectionUpdate)
        # 判断是否存在升级包
        gf = fs.list()
        if len(gf) <= 0:
            return 'ok', '', ''

        # 获取最后插入的那个升级包
        filename = fs.get_last_version().filename
        # 获取版本号
        serverVersion = filename.split("_")[1]
        # 只要版本不同就可以升级
        if state == 'permit' and serverVersion != softVersion:
            return 'upgrade', serverVersion, filename
        else:
            return 'ok', '', ''
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def get_file_from_mongo(filename):
    '''
    下载升级包
    '''
    try:
        softpath = f'{soft_path}/{filename}'
        if os.path.exists(softpath) is True:
            return send_from_directory(soft_path, filename, as_attachment=True)
        
        mg_client = get_mongo_client()
        db = mg_client[dbSynUpdate]
        fs = GridFS(db, collectionUpdate)  
        # 获取文件名
        gf = fs.list()
        if len(gf) <= 0:
            return None

        file = fs.find_one({"filename": filename})
        if file is not None:
            file_data = fs.get_version(filename=filename).read()        
            with open(softpath, 'wb') as file_w:
                file_w.write(file_data)
                
            return send_from_directory(soft_path, filename, as_attachment=True)
        
        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def getApkVersion():
    '''
    获取升级包版本号
    '''
    try:
        mg_client = get_mongo_client()
        db = mg_client[dbSynUpdate]
        fs = GridFS(db, collectionUpdate)
        # 获取文件名
        gf = fs.list()
        if len(gf) <= 0:
            return None
            
        # 获取最后插入的那个升级包
        filename = fs.get_last_version().filename
        serverVersion = filename.split("_")[1]

        return serverVersion
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def getUpgradeapkList():
    '''
    获取所有APP升级包列表
    '''
    try:
        mg_client = get_mongo_client()
        db = mg_client[dbSynUpdate]
        fs = GridFS(db, collectionUpdate)
        apkList = []
        res = fs.find()
        for v in res:
            O_Id = ObjectId(v._id)
            gf = fs.get(file_id=O_Id)
            data = {
                'fileName': gf.filename,
                'fileVersion': gf.version,
                'versionDesc': gf.version_desc
            }
            apkList.append(data)

        return apkList
    except Exception as e:
        raise ErrMongoClient.data(str(e))